package com.mtons.mblog.web.controller.site;

import com.mtons.mblog.base.lang.Consts;
import com.mtons.mblog.base.lang.Result;
import com.mtons.mblog.base.utils.MarkdownUtils;
import com.mtons.mblog.modules.data.AccountProfile;
import com.mtons.mblog.modules.data.AnswerVO;
import com.mtons.mblog.modules.data.PostVO;
import com.mtons.mblog.modules.data.QuestVO;
import com.mtons.mblog.modules.entity.Answer;
import com.mtons.mblog.modules.entity.Channel;
import com.mtons.mblog.modules.entity.Quest;
import com.mtons.mblog.modules.service.AnswerService;
import com.mtons.mblog.modules.service.ChannelService;
import com.mtons.mblog.modules.service.QuestService;
import com.mtons.mblog.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.View;

/**
 * 问答板块的controller
 *
 * @author Logan
 */
@Controller
public class QuestionAnswerController extends BaseController {

    @Autowired
    private QuestService questService;
    @Autowired
    private AnswerService answerService;

    @RequestMapping("/quest")
    public String questIndex(ModelMap model, HttpServletRequest request) {
        String order = ServletRequestUtils.getStringParameter(request, "order", Consts.order.NEWEST);
        int pageNo = ServletRequestUtils.getIntParameter(request, "pageNo", 1);
        model.put("order", order);
        model.put("pageNo", pageNo);

        return view(Views.QUESTION_INDEX);
    }

    @RequestMapping("/quest/{id:\\d*}")
    public String questView(@PathVariable Long id, ModelMap model) {
        QuestVO view = questService.get(id);

        Assert.notNull(view, "该问题已被删除");

        if ("markdown".endsWith(view.getEditor())) {
            QuestVO quest = new QuestVO();
            BeanUtils.copyProperties(view, quest);
            quest.setContent(MarkdownUtils.renderMarkdown(view.getContent()));
            view = quest;
        }
        questService.identityViews(id);
        model.put("view", view);
        return view(Views.QUEST_VIEW);
    }

    @RequestMapping("/answer/{answerId:\\d*}")
    public String answerView(@PathVariable Long answerId, ModelMap model) {
        AnswerVO view =  answerService.get(answerId);

        Assert.notNull(view, "该回答已被删除");

        if ("markdown".endsWith(view.getEditor())) {
            AnswerVO answer = new AnswerVO();
            BeanUtils.copyProperties(view, answer);
            answer.setContent(MarkdownUtils.renderMarkdown(view.getContent()));
            view = answer;
        }
        answerService.identityViews(answerId);
        model.put("view", view);
        String url = Views.ANSWER_VIEW;
        return view(url);
    }

    @RequestMapping("/quest/delete/{id}")
    @ResponseBody
    public Result deleteQuest(@PathVariable Long id) {
        Result data;
        try {
            questService.delete(id, getProfile().getId());
            data = Result.success();
        } catch (Exception e) {
            data = Result.failure(e.getMessage());
        }
        return data;
    }

    @RequestMapping("/answer/delete/{id}")
    @ResponseBody
    public Result deleteAnswer(@PathVariable Long id) {
        Result data;
        try {
            answerService.delete(id, getProfile().getId());
            data = Result.success();
        } catch (Exception e) {
            data = Result.failure(e.getMessage());
        }
        return data;
    }

    /**
     * 发布问题页
     * @return
     */
    @GetMapping("/quest/editing")
    public String editQuestView(Long id, ModelMap model) {
        model.put("editing", true);
        String editor = siteOptions.getValue("editor");
        if (null != id && id > 0) {
            AccountProfile profile = getProfile();
            QuestVO view = questService.get(id);

            Assert.notNull(view, "该问题已被删除");
            Assert.isTrue(view.getAuthorId() == profile.getId(), "该问题不属于你");

            Assert.isTrue(view.getStatus() == Consts.STATUS_NORMAL, "请在后台编辑此问题");
            model.put("view", view);

            if (StringUtils.isNoneBlank(view.getEditor())) {
                editor = view.getEditor();
            }
        }
        model.put("editor", editor);
        return view(Views.QUEST_EDITING);
    }

    /**
     * 提交发布问题
     * @param quest
     * @return
     */
    @PostMapping("/quest/submit")
    public String postQuest(QuestVO quest) {
        Assert.notNull(quest, "参数不完整");
        Assert.state(StringUtils.isNotBlank(quest.getTitle()), "标题不能为空");
        Assert.state(StringUtils.isNotBlank(quest.getContent()), "内容不能为空");

        AccountProfile profile = getProfile();
        quest.setAuthorId(profile.getId());

        // 修改时, 验证归属
        if (quest.getId() > 0) {
            QuestVO exist = questService.get(quest.getId());
            Assert.notNull(exist, "问题不存在");
            Assert.isTrue(exist.getAuthorId() == profile.getId(), "该问题不属于你");
            questService.update(quest);
        } else {
            questService.post(quest);
        }
        return String.format(Views.REDIRECT_USER_HOME, profile.getId());
    }

    /**
     * 发布回答页
     * @return
     */
    @GetMapping("/answer/post/{questId:\\d*}")
    public String postAnswerView(@PathVariable Long questId, ModelMap model) {
        model.put("editing", true);
        String editor = siteOptions.getValue("editor");

        AccountProfile profile = getProfile();

        QuestVO quest = questService.get(questId);
        Assert.notNull(quest, "该问题已被删除");
        Assert.isTrue(quest.getStatus() == Consts.STATUS_NORMAL, "请在后台回答");

        if (StringUtils.isNoneBlank(quest.getEditor())) {
            editor = quest.getEditor();
        }

        model.put("questId", quest.getId());

        model.put("editor", editor);
        return view(Views.ANSWER_EDITING);
    }

    /**
     * 修改回答页
     * @return
     */
    @GetMapping("/answer/update/{answerId:\\d*}")
    public String editAnswerView(@PathVariable Long answerId, ModelMap model) {
        model.put("editing", true);
        String editor = siteOptions.getValue("editor");

        AccountProfile profile = getProfile();

        AnswerVO answer = answerService.get(answerId);
        QuestVO quest = questService.get(answer.getQuestId());
        Assert.notNull(answer, "该问题已被删除");
        Assert.isTrue(quest.getStatus() == Consts.STATUS_NORMAL, "请在后台回答");

        if (StringUtils.isNoneBlank(quest.getEditor())) {
            editor = quest.getEditor();
        }

        model.put("view", answer);
        model.put("editor", editor);
        return view(Views.ANSWER_EDITING);
    }

    /**
     * 发布回答
     * @return
     */
    @PostMapping("/answer/submit")
    public String postAnswer(AnswerVO answerVO) {
        Assert.notNull(answerVO, "参数不完整");
        Assert.state(StringUtils.isNotBlank(answerVO.getContent()), "内容不能为空");

        AccountProfile profile = getProfile();
        answerVO.setAuthorId(profile.getId());

        // 修改时, 验证归属
        if (answerVO.getId() > 0) {
            AnswerVO exist = answerService.get(answerVO.getId());
            Assert.notNull(exist, "回答不存在");
            Assert.isTrue(exist.getAuthorId() == profile.getId(), "该回答不属于你");

            answerService.update(answerVO);
        } else {
            answerService.post(answerVO);
        }
        return String.format(Views.REDIRECT_USER_HOME, profile.getId());
    }
}
